<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="80px">
      <el-form-item label="登录名称">
        <el-input disabled v-model="userForm.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="update" type="primary">提交修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 辅助函数
import { mapState } from 'vuex'

export default {
  name: 'UserInfo',
  data () {
    return {
      // data 比 computed 更早一点初始化, 所以在 computed 里可以使用 data 中的数据, 而 data 中不能使用 computed 的数据, 如果非要使用, 可以等 computed 加载完毕后使用
      userForm: {
        // username: this.$store.state.user.userInfo.username,
        // nickname: this.$store.state.user.userInfo.nickname,
        // email: this.$store.state.user.userInfo.email
        username: '',
        nickname: '',
        email: ''
      },
      userRules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是 1 ~ 10 位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确格式的邮箱', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // console.log(this.userInfo.username)
    // this.userForm.username = this.userInfo.username
    // this.userForm.nickname = this.userInfo.nickname
    // this.userForm.email = this.userInfo.email

    // this.userForm = this.userInfo

    // 让两个对象不要引用同一个地址即可, 但属性的内容又要完全一样, 复制一份
    // 对象浅拷贝
    this.userForm = { ...this.userInfo }

    // 核心 API 的方法
    // Object.assign(this.userForm, this.userInfo)
  },
  computed: {
    // 映射 vuex 中的 userInfo
    ...mapState('user', ['userInfo'])
  },
  methods: {
    reset () {
      // Fields: 字段
      // 将所有字段重置为初始值
      this.$refs.userForm.resetFields()
    },
    update () {
      // 1. 兜底校验
      this.$refs.userForm.validate(async valid => {
        if (!valid) return
        // 2. 校验通过后发请求
        const { data: res } = await this.$http.put('/my/userinfo', this.userForm)
        // 3. 根据结果提示用户
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 4. 重新获取用户信息
        this.$store.dispatch('user/getUserInfo')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
